﻿{extend name="public:base" /}

{block name="css"}
<link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css"/>
<link rel="stylesheet" type="text/css" href="__ADMIN__/css/style.css">{/block}

{block name="content"}

<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox ">
                <div class="ibox-content">
                    <form method="post">
                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">视频</label>
                                <div class="col-sm-3">
                                    <input type="file" id="upload_file" accept=".mp4,.mov,.flv,.mkv" style="display: none">
                                    <input type="hidden" name="path" id="file" value="{$info['path']|default=''}"/>
                                    <input type="hidden" name="file_id" id="file_id" value="{$info['file_id']|default=''}"/>
                                    <div class="btn btn-primary btn-lg" id="up_file_btn">上传视频</div>
    <div class="progress-container mt-2" style="display: none;">
        <div class="progress" style="height: 10px; background-color: #f1f1f1; border-radius: 5px;">
            <div id="progress-bar" class="progress-bar" role="progressbar" style="width: 0%; background-color: #1ab394; border-radius: 5px;"></div>
        </div>
        <div id="progress-text" class="text-muted mt-1 text-sm"></div>
    </div>
                                </div>
                            </div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row video-box" style="display: none">
                                <label class="col-sm-1 col-form-label"></label>
                                <div class="col-sm-3">
                                    <video id="audio" controls style="max-height: 300px" src="{$info['path']}"></video>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">名称</label>
                                <div class="col-sm-3">
                                    <input type="text" class="form-control" name="name" value="{$info.name}">
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row">
                                <label class="col-sm-1 col-form-label">虚拟点赞数</label>
                                <div class="col-sm-3">
                                    <input type="number" class="form-control" name="zan_count" value="{$info.zan_count}">
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row layui-form">
                                <label class="col-sm-1 col-form-label">所属套餐</label>
                                <div class="col-sm-3">
                                    <select name="meal_id">
                                        <option value="">请选择</option>
                                        {volist name="meal_list" id="vo"}
                                        <option value="{$vo.id}" {$vo.id== $info.meal_id ? 'selected' : ''}>{$vo.name}</option>
                                        {/volist}
                                    </select>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="box-item">
                            <div class="form-group row layui-form">
                                <label class="col-lg-1 col-form-label">状态：</label>
                                <div class="col-lg-3">
                                    <input type="radio" name="status" value="1" title="启用" {$info.status !=-1 ? 'checked' : ''}>
                                    <input type="radio" name="status" value="-1" title="禁用" {$info.status== -1 ? 'checked' : ''}>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                        </div>

                        <div class="form-group row">
                            <div class="col-sm-4 col-sm-offset-2">
                                <button type="button" class="btn btn-w-m btn-default back-page">返回</button>
                                <button type="button" class="btn btn-w-m btn-primary ajax-post">提交</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>{/block}


{block name='js'}
<script src="__STATIC__/layui/layui.js"></script>
<!-- 引入HLS播放器库，用于播放M3U8格式视频 -->
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.4.12/dist/hls.min.js"></script>
<script>
    var path = '{$info.path}';

    if (path) {
        $('.video-box').show();
        
        // 初始化视频播放
        var video = document.getElementById('audio');
        
        // 检查视频路径是否为M3U8格式
        if (path.endsWith('.m3u8')) {
            $('#audio').attr('src', '');
            
            if (Hls.isSupported()) {
                var hls = new Hls();
                hls.loadSource(path);
                hls.attachMedia(video);
                hls.on(Hls.Events.MANIFEST_PARSED, function() {
                    console.log('M3U8文件解析完成，准备播放');
                });
            } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
                // 如果浏览器原生支持HLS
                video.src = path;
            }
        }
    }

    // 显示文件选择对话框
    $('#up_file_btn').click(function () {
        console.log('up_file_btn click')
        $('#upload_file').trigger('click');
    });

    // 文件选择变化时触发上传
    $('#upload_file').change(function () {
        var pic = $(this)[0].files[0];
        console.log('run upload_file')
        console.log(pic)
        if (!pic) return;

        // 检查文件类型是否为MP4
        var fileType = pic.type;
        if (fileType !== 'video/mp4') {
            layer.msg('请上传MP4格式的视频文件');
            return;
        }

        var formData = new FormData();
        // 调用新的视频上传接口
        var url = "/Upload/UploadFile/uploadVideoToM3U8";
        var name = pic['name'];

        formData.append('download', pic);
        formData.append('name', name);

        // 显示进度条
        $('.progress-container').show();
        $('#progress-bar').width('0%');
        $('#progress-text').text('准备上传...');

        // 使用XMLHttpRequest实现上传进度监控
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        
        // 设置超时时间为10分钟（600000毫秒）
        xhr.timeout = 600000;

        // 上传进度事件
        xhr.upload.addEventListener('progress', function (e) {
            if (e.lengthComputable) {
                var percentComplete = Math.round((e.loaded / e.total) * 100);
                $('#progress-bar').width(percentComplete + '%');
                if (percentComplete < 100) {
                    $('#progress-text').text('上传中: ' + percentComplete + '%');
                } else {
                    $('#progress-text').text('上传完成，正在处理视频...');
                }
            }
        }, false);

        // 完成事件
        xhr.onload = function () {
            if (xhr.status === 200) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    if (data.status == 1) {
                        clearFile('upload_file');

                        var fileId = data.data.id;
                        var fileName = data.data.name;
                        var status = data.data.status;
                        var processMessage = data.data.process_message;
                        
                        // 设置file_id到隐藏字段
                        $('#file_id').val(fileId);
                        
                        $('.video-box').show();
                        
                        // 显示处理状态
                            $('#progress-text').text(processMessage || '视频上传成功，正在转换中...');
                            layer.msg(data.msg || '视频上传成功！M3U8转换将在后台进行');
                            
                            // 立即使用MP4地址播放，不再等待M3U8转换完成
                            // MP4地址是我们上传的原始视频路径
                            $.ajax({
                                url: '/Upload/UploadFile/getVideoInfo',
                                type: 'POST',
                                data: {file_id: fileId}, 
                                dataType: 'json',
                                success: function(response) {
                                    if (response.status == 1 && response.data) {
                                        // 使用原始MP4文件路径作为视频源
                                        var mp4Path = response.data.original_path || '';
                                        if (mp4Path) {
                                            $('#audio').attr('src', mp4Path);
                                            $('#file').val(mp4Path); // 直接使用MP4路径入库
                                            console.log('已使用MP4路径进行播放:', mp4Path);
                                        }
                                    }
                                }
                            });
                        
                    } else {
                        layer.msg(data.msg || data.info || '上传失败');
                        $('#progress-text').text('上传失败: ' + (data.msg || data.info || '未知错误'));
                    }
                } catch (e) {
                    console.error('解析响应失败:', e);
                    layer.msg('处理响应失败，请重试');
                    $('#progress-text').text('处理响应失败');
                }
            } else {
                console.log('HTTP错误状态码:', xhr.status);
                var errorMsg = '上传请求失败';
                if (xhr.status === 404) {
                    errorMsg = '请求的资源未找到，可能是服务器配置问题';
                } else if (xhr.status === 500) {
                    errorMsg = '服务器内部错误，请稍后重试';
                }
                layer.msg(errorMsg);
                $('#progress-text').text(errorMsg);
            }
        };

        // 错误事件
        xhr.onerror = function () {
            layer.msg('网络错误，请检查网络连接');
            $('#progress-text').text('网络错误');
        };
        
        // 超时事件
        xhr.ontimeout = function() {
            console.log('请求超时');
            layer.msg('视频处理时间过长，请稍后查看或重试');
            $('#progress-text').text('处理超时，但视频可能仍在处理中');
        };

        // 发送请求
        xhr.send(formData);
    });

    // 确保clearFile函数已定义
    function clearFile(id) {
        document.getElementById(id).value = '';
    }
    
    // 轮询检查视频处理状态
    function startCheckingVideoStatus(fileId, fileName) {
        var checkInterval = 3000; // 每3秒检查一次
        var maxChecks = 200; // 最多检查200次（10分钟）
        var checkCount = 0;
        
        var checkTimer = setInterval(function() {
            checkCount++;
            
            if (checkCount > maxChecks) {
                clearInterval(checkTimer);
                $('#progress-text').text('视频处理超时，请手动刷新页面查看');
                layer.msg('视频处理时间较长，请稍后刷新页面查看', {icon: 5});
                return;
            }
            
            // 发送请求检查视频状态
            $.ajax({
                url: '/Upload/UploadFile/getVideoStatus',
                type: 'POST',
                data: {file_id: fileId},
                dataType: 'json',
                success: function(response) {
                    if (response.status == 1) {
                        var status = response.data.status;
                        var processMessage = response.data.process_message || '';
                        
                        // 更新进度文本
                        $('#progress-text').text(processMessage || '视频正在转换中...');
                        
                        if (status == 2) {
                            // 处理完成
                            clearInterval(checkTimer);
                            loadAndPlayVideo(fileId, fileName);
                        } else if (status == 3) {
                            // 处理失败
                            clearInterval(checkTimer);
                            $('#progress-text').text('视频转换失败: ' + processMessage);
                            layer.msg('视频转换失败: ' + processMessage, {icon: 5});
                        }
                    } else {
                        console.error('获取视频状态失败:', response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取视频状态请求失败:', error);
                }
            });
        }, checkInterval);
    }
    
    // 加载并播放视频
    function loadAndPlayVideo(fileId, fileName) {
        $.ajax({
            url: '/Upload/UploadFile/getVideoInfo',
            type: 'POST',
            data: {file_id: fileId},
            dataType: 'json',
            success: function(response) {
                if (response.status == 1 && response.data && response.data.path) {
                    var m3u8Path = response.data.path;
                    $('#audio').attr('src', '');
                    var video = document.getElementById('audio');
                    
                    if (Hls.isSupported()) {
                        var hls = new Hls();
                        hls.loadSource(m3u8Path);
                        hls.attachMedia(video);
                        hls.on(Hls.Events.MANIFEST_PARSED, function() {
                            console.log('M3U8文件解析完成，准备播放');
                            $('#progress-text').text('视频转换完成，准备播放');
                        });
                        hls.on(Hls.Events.ERROR, function(event, data) {
                            console.error('HLS播放错误:', data);
                            layer.msg('视频播放错误: ' + data.details);
                        });
                    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
                        // 如果浏览器原生支持HLS
                        video.src = m3u8Path;
                        video.addEventListener('loadedmetadata', function() {
                            console.log('原生HLS播放准备就绪');
                            $('#progress-text').text('视频转换完成，准备播放');
                        });
                    }
                    
                    // 存储M3U8路径到隐藏字段
                    $('#file').val(m3u8Path);
                    
                    // 显示成功消息
                    layer.msg('视频转换成功！', {icon: 6});
                    $('#progress-text').text('视频转换完成！');
                } else {
                    $('#progress-text').text('获取视频信息失败');
                    layer.msg('获取视频信息失败，请刷新页面重试', {icon: 5});
                }
            },
            error: function(xhr, status, error) {
                console.error('获取视频信息请求失败:', error);
                $('#progress-text').text('获取视频信息失败');
                layer.msg('获取视频信息失败，请刷新页面重试', {icon: 5});
            }
        });
    }
</script>{/block}